﻿Imports System.Web
Imports System.Web.Services
Imports System.IO

Public Class Receiver
    Implements System.Web.IHttpHandler

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim filename As String = context.Request.QueryString("filename").ToString()
        Dim iddoc As String = context.Request.QueryString("iddoc").ToString()

        If Not Directory.Exists(context.Server.MapPath("~/Documents")) Then
            Directory.CreateDirectory(context.Server.MapPath("~/Documents"))
        End If

        Using fs As FileStream = File.Create(context.Server.MapPath("~/Documents/" & iddoc & "_" & filename))
            SaveFile(context.Request.InputStream, fs)
        End Using
    End Sub

    Private Sub SaveFile(ByVal stream As Stream, ByVal fs As FileStream)
        Dim buffer As Byte() = New Byte(4095) {}
        Dim bytesRead As Integer

        bytesRead = stream.Read(buffer, 0, buffer.Length)
        While bytesRead <> 0
            fs.Write(buffer, 0, bytesRead)
            bytesRead = stream.Read(buffer, 0, buffer.Length)
        End While
    End Sub

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class